﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace Studentpartners.Sightseeing.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private Boolean _isDataLoaded = false;

        public MainViewModel()
        {
            Items = new ObservableCollection<SightViewModel>();
        }

        public ObservableCollection<SightViewModel> Items { get; private set; }

        public Boolean IsDataLoaded
        {
            get { return _isDataLoaded; }
            set
            {
                if (value != _isDataLoaded)
                {
                    _isDataLoaded = value;
                    NotifyPropertyChanged("IsDataLoaded");
                }
            }
        }

        public void LoadData()
        {
            int idCounter = 1;
            XDocument doc = XDocument.Load("Ortsliste.kml",LoadOptions.SetLineInfo);
            XNamespace nsp = XNamespace.Get("http://earth.google.com/kml/2.1"); //Problem solution!!!!!

            


            foreach (XElement e in doc.Descendants(nsp + "kml").Descendants(nsp + "Document").Descendants(nsp + "Placemark"))
            {
                SightViewModel aktSVM = new SightViewModel();

                aktSVM.Id = idCounter;

                foreach (XElement NameEle in e.Descendants(nsp + "name"))
                {
                    aktSVM.Title = NameEle.Value;
                }

                foreach (XElement DescEle in e.Descendants(nsp + "description"))
                {
                    // HTML decode
                    aktSVM.Description = HttpUtility.HtmlDecode(DescEle.Value);

                }

                foreach (XElement CordEle in e.Descendants(nsp + "Point").Descendants(nsp + "coordinates"))
                {
                   String cords = CordEle.Value;

                   String[] cordsArray = cords.Split(',');

                   aktSVM.Longitude = double.Parse(cordsArray[0], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo);

                   aktSVM.Latitude = double.Parse(cordsArray[1], System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberFormatInfo.InvariantInfo); 
                }

                this.Items.Add(aktSVM);
                idCounter++;
            }
            IsDataLoaded = true;
        }
    }
}
